package com.example.midushop.controller;

import com.example.midushop.entity.customer.CustomerLogin;
import com.example.midushop.service.customer.impl.CustomerInfoServiceImpl;
import com.example.midushop.service.customer.impl.CustomerLoginServiceImpl;
import com.example.midushop.util.R;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Date;

/** 短信验证API接口控制器*/
@RestController
@RequestMapping("/api/CustomerLogin")
public class LoginContr {
    @Autowired
    CustomerLoginServiceImpl customerLoginService; // 注入账号登录服务类
    @Autowired
    CustomerInfoServiceImpl customerInfoService;  // 注入用户信息服务类

    public static final String ACCOUNT_ID = "797952";//这里填写你在平台里的ACOUNT_ID
    public static final String ACCOUNT_SID = "96d5141f2bdd84b64a9bb92c247de9f7";//这里填写你在平台里的ACOUNT_SID
    public static final String AUTH_TOKEN = "122aa54e865ef76fee98d792a5ee1a0f";//这里填写你在平台里的AUTH_TOKEN
    public static final String BASE_URL = "https://openapi.miaodiyun.com/distributor/sendSMS";//请求地址是固定的不用改
    public int randNum;
    public int getRandNum(){
        randNum = (int)((Math.random()*9+1)*100000);
        return randNum;
    }
    //短信模板
    /**
     * 测试短信发送（平台：秒嘀科技），测试通过，可用=================================
     * @param to  接收信息手机号
     * @return
     */
    @RequestMapping(value = "/sms/{to}" ,method = RequestMethod.GET)
    public String sendSMSG(@PathVariable("to") String to){
        getRandNum(); //调用函数
        String smsContent = "【海河龙珠科技】亲爱的用户，您的短信验证码为"+randNum+"，,1分钟内有效，若非本人操作请忽略。";
        //设置时间戳
        String timeStamp1 = String.valueOf(new Date().getTime());
        String timeStamp = timeStamp1;
        System.out.println(timeStamp);
        //各个数据经过MD5加密之后返回sig
        String sig=MD5(ACCOUNT_SID,AUTH_TOKEN,timeStamp);
        String str = "accountId="+ACCOUNT_ID+"&accountSid="+ACCOUNT_SID+"&smsContent="+
                smsContent+"&to="+to+"&timestamp="+timeStamp+"&sig="+sig;

        OutputStreamWriter out = null;
        InputStream in = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        try {
            URL url = new URL(BASE_URL);
            URLConnection connection = url.openConnection();//打开连接
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);  //设置链接超时
            connection.setReadTimeout(10000);    //设置读取超时
            out = new OutputStreamWriter(connection.getOutputStream(),"utf-8");
            out.write(str);
            out.flush();
            //读取返回数据
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            while((line = br.readLine())!=null){
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = JSONObject.fromObject(sb.toString());
        System.out.println(jsonObject);
        Object object = jsonObject.get("respCode");
        System.out.println("状态码："+object+"验证码："+randNum);
        System.out.println(!object.equals("00000"));
        return jsonObject.toString();
    }

    //MD5算法
    public static String MD5(String... args){ //动态参数
        StringBuffer result = new StringBuffer();
        if (args == null || args.length == 0) {
            return "";
        } else {
            StringBuffer str = new StringBuffer();
            for (String string : args) {
                str.append(string);
            }
            System.out.println("加密前：\t"+str.toString());

            try {
                MessageDigest digest = MessageDigest.getInstance("MD5");
                byte[] bytes = digest.digest(str.toString().getBytes());
                for (byte b : bytes) {
                    String hex = Integer.toHexString(b&0xff);  //转化十六进制
                    if (hex.length() == 1) {
                        result.append("0"+hex);
                    }else{
                        result.append(hex);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("加密后：\t"+result.toString());
        return result.toString();
    }

    //登录验证
    @GetMapping("/findLoginSMSG/{phone}&&{sms}")
    public R findLoginSMSG(@PathVariable("phone") String phone,@PathVariable("sms") int sms){
        if(sms==randNum){
            CustomerLogin customerLogin = customerLoginService.findLoginNumber(phone,null);
            if(customerLogin==null){
                return R.ok("该账号未注册,是否立即注册？");
            }else {
                return R.ok(customerInfoService.findLoginUserInfo(customerLogin.customer_id));
            }
        }else {
            return  R.ok("验证码输入错误,请重新输入!");
        }
    };

    @GetMapping("/Login")
    public R findLogin(@RequestParam("name") String login_name,@RequestParam("password") String password){
        CustomerLogin  customerLogin = customerLoginService.findLoginNumber(login_name,password);
        if(customerLogin==null){
            return R.ok("该账号未注册,是否立即注册？");
        }else {
            return R.ok(customerInfoService.findLoginUserInfo(customerLogin.customer_id));
        }
    }
}